package interview.huawei.tjt.training.huaweijishitiku;

import java.util.Scanner;

// 成绩排序
public class HJ68 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        while ( sc.hasNextLine() ) {

            int n = Integer.parseInt(sc.nextLine());
            int flag = Integer.parseInt(sc.nextLine());

            String[][] grade = new String[n][2];

            for ( int i = 0; i < n; i ++ ) {
                String str = sc.nextLine();
                String[] strings = str.split(" ");
                grade[i][0] = strings[0];
                grade[i][1] = strings[1];
            }

            // 由低到高
            if ( flag == 1 ) {
                for ( int i = 0; i < n; i ++ ) {
                    for ( int j = n - 1; j > i; j -- ) {
                        if ( Integer.parseInt(grade[j - 1][1]) > Integer.parseInt(grade[j][1]) ) {
                            String temp = grade[j - 1][1];
                            grade[j - 1][1] = grade[j][1];
                            grade[j][1] = temp;

                            String name = grade[j - 1][0];
                            grade[j - 1][0] = grade[j][0];
                            grade[j][0] = name;
                        }
                    }
                }
            }

            // 由高到低
            if ( flag == 0 ) {
                for ( int i = 0; i < n; i ++ ) {
                    for ( int j = n - 1; j > i; j -- ) {
                        if ( Integer.parseInt(grade[j - 1][1]) < Integer.parseInt(grade[j][1]) ) {
                            String temp = grade[j - 1][1];
                            grade[j - 1][1] = grade[j][1];
                            grade[j][1] = temp;

                            String name = grade[j - 1][0];
                            grade[j - 1][0] = grade[j][0];
                            grade[j][0] = name;
                        }
                    }
                }
            }

            for ( int i = 0; i < n; i ++ ) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(grade[i][0]).append(" ").append(grade[i][1]);
                System.out.println(stringBuffer);
            }

        }

    }

}
